import * as qiniu from "qiniu-js";
import MediaApi from "../api/MediaApi"
// import {slidesOnLeft} from "ant-design-vue/es/vc-slick/src/utils/innerSliderUtils";


/* ------------------------ 导出 ------------------------ */
let uploadToken = "";
let MediaManager = {

    getMediaBase() {
        if (process.env.NODE_ENV === "development") {
            return "https://imagetest.pxparking.com"
        } else {
            return "https://image.pxparking.com";
        }
    },

    /* ------------------------ 获取素材 ------------------------- */
    getMediaOrigin({ path, isStatic = false }) {
        if (path.indexOf("blob:") != -1) return path;
        if (path.indexOf("http") != -1 || path.indexOf("https") != -1) return path;
        let r = this.getMediaBase() + path
        if (isStatic) r += "?imageView2/2/format/jpg";
        return r;
    },

    getPictureThumb({ path, width }) {
        if (!path) return "";
        if (path.indexOf("http://") == -1 && path.indexOf('https://') == -1) {
            path = this.getMediaBase() + path;
        }
        return path + `?imageView2/2/w/${width}`;
    },

    getVideoThumb({ offset = 0, width, height, path }) {
        if (!path) return "";
        if (path.indexOf("http://") == -1 && path.indexOf('https://') == -1) {
            path = this.getMediaBase() + path;
        }
        return path + `?vframe/png/offset/${offset}/w/${width}/h/${height}`
    },
    // 高德地图key配置
    getLocationMap({ latitude, longitude, width = 319, height = 136 }) {
        let key = 'cde493f4505eae9dfb8f09bcfa635e81';
        let appname = 'cde493f4505eae9dfb8f09bcfa635e81';
        let MAP_DOMAIN = "https://restapi.amap.com/v3/staticmap";
        return `${MAP_DOMAIN}?key=${key}&s=rsx&platform=WXJS&appname=${appname}&sdkversion=1.2.0&logversion=2.0&location=${longitude},${latitude}&zoom=15&size=${width}*${height}&scale=1&markers=mid,0xFF0000,:${longitude},${latitude}`;
    },

    /* ------------------------ 上传 ------------------------- */
    uploadFile({ file, fileName }) {
        // 登录态存在的时候
        if (uploadToken) return upload({ file, fileName });
        // 未登录
        return MediaApi.getUploadToken().then(({ data }) => {
            uploadToken = data.uptoken;
            return upload({ file, fileName });
        })
    },

    uploadBatchFile({ fileList, prefix }) {
        if (uploadToken) return uploadBatch({ fileList, prefix });
        if (fileList.length == 0) return Promise.resolve();
        return MediaApi.getUploadToken().then(({ data }) => {
            uploadToken = data.uptoken;
            return uploadBatch({ fileList, prefix });
        })
    },

    uploadBase64({ base64 }) {
        if (uploadToken) return uploadBase64(base64);
        return MediaApi.getUploadToken().then(({ data }) => {
            uploadToken = data.uptoken;
            return uploadBase64(base64);
        })
    },
}
export default MediaManager;


/* ------------------------ 私有 ------------------------ */
function upload({ file, fileName, prefix }) {
    if (file == undefined) {
        return Promise.reject({ data: "上传文件不能为空" });
    }

    /* -------------------- 当前文件已经上传了 ------------------------- */
    if (file.$key) {
        return Promise.resolve({ data: file.$key })
    }

    /* ------------------------ 正式上传 ------------------------------- */
    fileName = file.name;
    fileName = prefix == undefined || '' ? '' : prefix + fileName;


    let observable = qiniu.upload(file, fileName, uploadToken, {}, {
        region: qiniu.region.z2,
        disableStatisticsReport: true
    })

    return new Promise((resolve, reject) => {
        let complete = (res) => {
            file.$key = res.key
            resolve({ data: res.key })
        }
        let error = (res) => {
            if (res.code == 401) uploadToken = "";
            reject({ data: res.message, code: res.code })
        }
        observable.subscribe(undefined, error, complete)
    })
}

const UPLOAD_BASE64_URL = "http://upload-z2.qiniup.com/putb64/-1";

function uploadBase64(base64) {
    if (!base64) return Promise.reject("上传文件不能为空");
    base64 = base64.replace("data:image/jpeg;base64,", "");

    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        /* 回调 */
        xhr.onreadystatechange = function() {
            if (xhr.readyState != 4) return

            if (xhr.status == 200) {
                let text = xhr.response;
                if (text && typeof text == 'string') text = JSON.parse(text)
                resolve({ data: text.key }); // 返回图片地址
            } else {
                if (xhr.code == 401) uploadToken = "";
                reject({ data: "网络异常", code: xhr.code })
            }
        }
        xhr.onerror = reject
        xhr.open("POST", UPLOAD_BASE64_URL, true);
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.setRequestHeader("Authorization", `UpToken ${uploadToken}`);
        xhr.send(base64);
    })
}

function uploadBatch({ fileList, index = 0, prefix }) {
    if (index == fileList.length) {
        return Promise.resolve();
    }
    let file = fileList[index];
    return upload({ file, prefix }).then(() => {
        return uploadBatch({ fileList, index: index + 1, prefix })
    })
}